package org.soma.sso.server.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soma.sso.core.constant.ConfigConstant;
import org.soma.sso.core.store.CookieStore;
import org.soma.sso.core.store.SsoStore;
import org.soma.sso.core.utils.CookieUtils;
import org.soma.sso.server.exception.SsoException;
import org.soma.sso.server.mapper.SomaSsoUserMapper;
import org.soma.sso.server.model.SomaSsoUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("sso")
public class LoginController {
	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private SomaSsoUserMapper somaSsoUserMapper;

	@RequestMapping(value = "goLogin", method = { RequestMethod.GET,	RequestMethod.POST })
	public String goLoign(HttpServletRequest request){
		 String requestURL= request.getRequestURL().toString();
		 ModelAndView modelAndView = new ModelAndView();
		 modelAndView.addObject("requestURL", requestURL);
		 return "login.html";
	}


	@RequestMapping(value = "login", method = { RequestMethod.GET,	RequestMethod.POST })
	@ResponseBody
	public ResponseResult<Map<String, Object>> login(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "callbackURL", required = false) String callbackURL,
			@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "password", required = false) String password) {
		ResponseResult<Map<String, Object>> responseResult = new ResponseResult<Map<String, Object>>();
		try {
			String sessionId = UUID.randomUUID().toString();
			if (StringUtils.isBlank(username)) {
				throw new SsoException("000001", "用户名不能为空!");
			}
			if (username == null && password == null) {
				throw new SsoException("000002", "密码不能为空!");
			}
			System.out.println(request.getRequestURL().toString());
			SomaSsoUser querySomaSsoUser = new SomaSsoUser();
			querySomaSsoUser.setUsername(username);
			SomaSsoUser somaSsoUser =somaSsoUserMapper.querySomaSsoUser(querySomaSsoUser);
			if (somaSsoUser !=null && username.equals(somaSsoUser.getUsername())) {
				if(password.equals(somaSsoUser.getPassword())) {
					CookieStore.setSessionIdInCookie(response, sessionId);
					SsoStore.put(sessionId, somaSsoUser);
					Map<String, Object> requestURLMap = new HashMap<String, Object>();
					if(StringUtils.isNotBlank(callbackURL)){
						requestURLMap.put("callbackURL", callbackURL+"?token="+sessionId);
					}
					responseResult.setResultObj(requestURLMap);
				}else{
					throw new SsoException("000001", "密码不正确");
				}
			} else {
				throw new SsoException("000001", "用户名不存在");
			}
		} catch (SsoException sso) {
			responseResult.setResultMsg(sso.getErrorMsg());
			responseResult.setResultCode(sso.getErrorCode());
			logger.error(sso.getErrorMsg(), sso);
		} catch (Exception e) {
			responseResult.setResultMsg("");
			responseResult.setResultCode("999999");
			logger.error("", e);
		}
		return responseResult;
	}



	@RequestMapping(value="verifyToken", method = RequestMethod.POST,
			produces={"application/json; charset=UTF-8"},
			headers={"Content-Type=application/x-www-form-urlencoded","Content-Type=application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseResult<String> verifyToken(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "token") String token) {
		ResponseResult<String> responseResult = new ResponseResult<String>();
		try {
			Object object =SsoStore.get(token);
			if (object!=null && StringUtils.isNotBlank(token) ) {
				responseResult.setResultObj("true");
			} else {
				responseResult.setResultObj("false");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return responseResult;
	}

	@RequestMapping(value = "logout", method = { RequestMethod.GET})
	public void logout(HttpServletRequest request,HttpServletResponse response) {
		try {
			String contextPath =request.getContextPath();
			String cookieSessionId = CookieStore.getSessionIdByCookie(request);
	        if (cookieSessionId != null) {
	            SsoStore.remove(cookieSessionId);
	        }
	        CookieUtils.remove(request, response, ConfigConstant.SSO_SESSIONID);
	        response.sendRedirect(contextPath+"/login.html");
		} catch (Exception e) {
			logger.error("", e);
		}
	}
}
